package com.abel.servicegoods.test;

public class ProducerConsumer {
    public static void main(String[] args) {
        Task task=new Task();
        new Thread(()->{
            try {
                for (int i = 0; i <30 ; i++) {
                    task.increment();
                }

            }catch (Exception e){
                e.printStackTrace();
            }

        },"A").start();
        new Thread(()->{
            try {
                for (int i = 0; i <30 ; i++) {
                    task.decrement();
                }
            }catch (Exception e){
                e.printStackTrace();
            }

        },"B").start();
    }
    static class Task{
        private static int num=0;
        public synchronized void increment() throws InterruptedException {
            if(num!=0){
                this.wait();
            }
            num++;
            System.out.println(num);
            this.notifyAll();
        }
        public synchronized void decrement() throws InterruptedException {
            if(num==0){
                this.wait();
            }
            num--;
            System.out.println(num);
            this.notifyAll();
        }
    }
}
